local app = require 'app'

local room = {}

room.state = 
{
    max_player = 3,
    playing_players = {};
}

local no2local = function(no)
    local self_no = app.game.running.kbe.player().seat.no
    if self_no > room.state.max_player then
        return no
    end

    return (no - self_no + room.state.max_player) % room.state.max_player + 1
end

room.mutations = 
{
    no2local = function(store, state, no)
        return no2local(no)
    end,

    on_enter = function(store, state, player)
        if player.seat.no > 0 then
            player.seat.local_no = no2local(player.seat.no)
            state.playing_players[player.seat.no] = player;
            app.game.running.gamelib.log.debug("玩家进入："..tostring(player.seat.no).."local_no"..tostring(player.seat.local_no))
            store.emit("玩家进入", player);
        end
    end,

    on_leave = function(store, state, player)
        for no, playing_player in pairs(state.playing_players) do
            if playing_player == player then
                state.playing_players[no] = nil;
                player.seat.no = no;
                app.game.running.gamelib.log.debug("玩家离开："..tostring(player.seat.no).."local_no"..tostring(player.seat.local_no))
                store.emit("玩家离开", player);    
                break;
            end
        end
    end,

    on_player_ready = function(store, state, player)
        if player.seat.local_no then
            store.emit('更新准备状态', player)
        else
            app.game.running.gamelib.log.debug("seat 还没有 就更新状态")
        end
    end
}

return room